<?php

namespace Managers;

class Pages extends BaseManager
{
    protected $__table = '\Catalog\Pages';

    public function qb()
    {

        return $this->_em->getRepository($this->__table)->createQueryBuilder('c');
    }

    public function getList($parent = null, $short = null)
    {
        $query = $short ? 'partial r.{id, title}' : 'r';
        $qb = $this->_em->createQueryBuilder()
                ->select($query)
                ->from($this->__table, 'r');
        if ($parent) {
            $qb = $qb->where('r.parent = :parent')
                    ->setParameter('parent', $parent);
        } else {
            $qb = $qb->where('r.parent is null');
        }

        $res = $qb->getQuery()
                ->getArrayResult();

        foreach ($res as $i => $record) {
            $res[$i]['children'] = $this->getList($record['id'], $short);
        }

        return $res;
    }

    public function getRoot($id)
    {

        $qb = $this->_em->createQueryBuilder()
                ->select('p', 'parent')
                ->from($this->__table, 'p')
                ->leftJoin('p.parent', 'parent')
                ->where('p.id = :id')->setParameter('id', $id)
                ->setMaxResults(1)
                ->getQuery()
                ->getArrayResult();

        $res = $qb[0];

        if (isset($res['parent'])) {
            $res = $this->getRoot($res['parent']['id']);
        }

        return $res;

    }

    /**
     * Сохраняет запись в БД с массива.
     * @throws \Exception Родительская страница и текущая - одинакова..
     * @param array $params
     * @return void
     * @author b179a9
     */
    function save(array $params)
    {
        $page = empty($params['id']) ? new \Catalog\Pages
                : $this->_em->find($this->__table, $params['id']);
        $page->setTitle($params['title']);
        $page->setSortOrder($params['sortOrder']);
        $page->setContent($params['content']);
        $page->setMenu($params['menu']);
        $parent = empty($params['parent']) ? null
                : $this->_em->getReference($this->__table, $params['parent']);
        if (!empty($params['id']) && $params['parent'] == $params['id']) {
            throw new \Exception('Page cannot be parent to itself.');
        }
        $page->setParent($parent);

        $page->setSortOrder($params['sortOrder']);
        $page->setUrl($params['url']);

        $this->_em->persist($page);
        $this->_em->flush();
    }

    /**
     * Изменяет родительскую страницу для Drag&Drop.
     * @param $id
     * @param $parent
     * @return void
     */
    function changeParent($id, $parent_id)
    {
        $page = $this->_em->find($this->__table, $id);

        if ($id == $parent_id) {
            return 0;
        }

        if ($page) {
            $parent = $parent_id != 0 ? $this->_em->find($this->__table, $parent_id) : null;
            $page->setParent($parent);

            $this->_em->persist($page);
            $this->_em->flush();
            return 1;
        }
        return 0;
    }

    public function getMenu($parent = null)
    {
        $cacheName = 'menu_' . $parent;
        $res = $this->_getCacheManager()->load($cacheName);

        if (!$res) {
            $qb = $this->_em->createQueryBuilder()
                    ->select('partial r.{id, title, url}')
                    ->from($this->__table, 'r')
                    ->orderby('r.id');
            if ($parent) {
                $qb = $qb->where('r.parent = :parent')
                        ->setParameter('parent', $parent);
            } else {
                $qb = $qb->where('r.parent is null');
            }

            $res = $qb->getQuery()
                    ->getArrayResult();

            foreach ($res as $i => $record) {
                $res[$i]['children'] = $this->getMenu($record['id']);
            }
            $this->_getCacheManager()->save($res, $cacheName);
        }

        return $res;
    }


}
